let ProjectManager = {}
let user_yffzr = {}
let user_xrxs = {}
let user_xrsq = {}
let user_ser_mana = {}

function AllReady() {
    var toolbar = Ext.getCmp("toolbar");
    var tabPanel = Ext.getCmp("tabPanel");
    addTabs(mstform, tabPanel, toolbar);
    var mstform = Ext.getCmp("formProjectTableMst");
    var dgrid = Ext.getCmp("gridEmpChgOther");
    var pc_stakeholders = Ext.getCmp("pc_stakeholders");
    var pc_stakeholders_store = pc_stakeholders.getStore();
    var pc_cnt_info = Ext.getCmp("pc_cnt_info");
    var pc_cnt_info_store = pc_cnt_info.getStore();

    mstform.items.items[4].hide();
    var formProjectTableProj = Ext.getCmp("formProjectTableProj");
    var formProjectTableSummary = Ext.getCmp("formProjectTableSummary");

    //toolbar.get("imp").setText("引用中标商机");

    var tabSummary = tabPanel.items.find(function (item) {
        return item.id === "tabSummary";
    });
    var tabProj = tabPanel.items.find(function (item) {
        return item.id === "tabProj";
    });
    var tabCorrect = tabPanel.items.find(function (item) {
        return item.id === "tabCorrect";
    });
    var tabCompany = tabPanel.items.find(function (item) {
        return item.id === "tabCompany";
    });
    var tabOther = tabPanel.items.find(function (item) {
        return item.id === "tabOther";
    });
    var tabPcmap = tabPanel.items.find(function (item) {
        return item.id === "tabPcmap";
    });

    if (tabPanel) {
    var tabsToHide = ["tabSummary", "tabCorrect", "tabCompany", "tabOther", "tabPcmap","tabProj"];

    tabsToHide.forEach(function (tabId) {
      var tab = tabPanel.getComponent(tabId).tab;
      if (tab) {
        tab.hide();
      }
    });
  }



    var user_product_line = mstform.getItem("user_product_line");
    var user_industry_line = mstform.getItem("user_industry_line");
    var user_profit_center_no = mstform.getItem("user_profit_center_no");
    var user_lrzx = mstform.getItem("user_lrzx");
    var user_cost_center_no = mstform.getItem("user_cost_center_no");
    var user_cbzx = mstform.getItem("user_cbzx");
    var PhIdFiOcode = mstform.getItem("PhIdFiOcode");
    var user_budget_org_no = mstform.getItem("user_budget_org_no");
    var user_yszz = mstform.getItem("user_yszz");
    var CatPhId = mstform.getItem("CatPhId");
    var user_division = mstform.getItem("user_division");

    var PhIdType = mstform.getItem("PhIdType");
    var user_country = mstform.getItem("user_country");
    var user_province = mstform.getItem("user_province");
    var user_city = mstform.getItem("user_city");
    var user_region = mstform.getItem("user_region");
    var Stat = mstform.getItem("Stat");


    var tabs = tabPanel.items.items;

    // for (var i = 1; i < tabs.length; i++) {
    //     tabPanel.setActiveTab(i);
    // }
    // 默认打开第一个tab页



    //console.log("gridEmpChgOther");
    // Ext?.getCmp("gridEmpChgOther").store.on(
    //     "remove",
    //     function (store, records, index, eOpts) {
    //         console.log(records.raw.id1, "被删除的数据");
    //         console.log(records.raw.id1 == undefined, "records.raw.id1==undefined");
    //         console.log(records.raw.id1 == 1, "records.raw.id1==undefined");
    //         console.log(records.raw.id1 == 2, "records.raw.id1==undefined");
    //         console.log(records.raw.id1 == 3, "records.raw.id1==undefined");
    //     }
    // );
    // if (otype == "view" && otype == "edit") {

    //     mstform.on("dataready", function () {
    //         if (mstform.getItem("user_sjbm").getValue() > 0) {
    //             execServer(
    //                 "GetStakeholdersInfo",
    //                 { sj: mstform.getItem("user_sjbm").getValue() },
    //                 function (res) {
    //                     if (res.count == 0) return
    //                     else if (res.count > 0) {
    //                         var obj = JSON.parse(res.data);
    //                         mstform.getItem("user_gxrid").setValue(obj[0].extendObjects.phid);
    //                     }
    //                 }
    //             );
    //         }
    //     });
    // }

    if (schemeid == '8570000000000335') {

        mstform.getItem('ApproxContractFc').setVisible(false);
        mstform.getItem('ApproxContractFc').userSetMustInput(false);
        mstform.getItem('PhIdCompany').userSetReadOnly(false)
        mstform.getItem('user_dslb').userSetReadOnly(false)
        mstform.getItem('user_sjbm').userSetMustInput(false);
        mstform.getItem('user_sjmc').userSetMustInput(false);
        //  mstform.getItem ('PhIdCompany').userSetMustInput(false);   
        //   mstform.getItem('PcNo').userSetReadOnly(false)
        mstform.getItem('user_country').userSetReadOnly(false)
        mstform.getItem('user_province').userSetReadOnly(false)
        mstform.getItem('user_city').userSetReadOnly(false)
        mstform.getItem('user_region').userSetReadOnly(false)
        mstform.getItem('user_product_line').userSetReadOnly(false)
        mstform.getItem('user_industry_line').userSetReadOnly(false)
        mstform.getItem('user_regional_center').userSetReadOnly(false)
        //mstform.getItem('StartDate').userSetReadOnly(false)
        mstform.getItem('user_ser_mana').userSetMustInput(false)
        mstform.getItem('user_xrxs').userSetMustInput(false)
        mstform.getItem('user_xrsq').userSetMustInput(false)
        mstform.getItem('user_yffzr').userSetMustInput(false)
        mstform.getItem('user_ser_mana').setVisible(false)
        mstform.getItem('user_xrxs').setVisible(false)
        mstform.getItem('user_xrsq').setVisible(false)
        mstform.getItem('user_yffzr').setVisible(false)


        mstform.getItem('user_sf_tqsg').setValue(0)

        mstform.getItem("user_regional_center").addListener("helpselected", function () {
            const ywfwValue = mstform.getItem("user_regional_center").getRawValue() || '';
            console.log('传递的参数 ywfw:', ywfwValue); // 确认参数是否正确
            execServer("GetYwfwInfo", { ywfw: mstform.getItem("user_regional_center").getRawValue() || '0' }, function (res) {
                console.log('业务范围', res)
                if (res.count == 0) return;

                else {
                    var obj = JSON.parse(res.data);
                    mstform.getItem("user_ywfw").setValue(obj[0].extendObjects.phid);
                    mstform.getItem("user_ywfw").setRawValue(obj[0].extendObjects.u_ywcj_name);
                    mstform.getItem("user_bus_range_no").setValue(obj[0].extendObjects.u_ywcj_no);

                }

            });
        });

        // Ext.getCmp("toolbar").get("imp").hide();

    }

    else if (schemeid == '8570000000000144') {

        mstform.getItem('ApproxContractFc').userSetMustInput(true);
        mstform.getItem('user_ser_mana').userSetMustInput(true)
        mstform.getItem('user_xrxs').userSetMustInput(true)

        mstform.getItem('user_sjbm').userSetMustInput(false);
        mstform.getItem('user_sjmc').userSetMustInput(false);
        mstform.getItem('user_regional_center').userSetReadOnly(false)
        //  mstform.getItem ('PhIdCompany').userSetMustInput(false);   
        toolbar.get("imp").setText("引用提前施工申请");
        mstform.getItem("user_regional_center").addListener("helpselected", function () {
            const ywfwValue = mstform.getItem("user_regional_center").getRawValue() || '';
            console.log('传递的参数 ywfw:', ywfwValue); // 确认参数是否正确
            execServer("GetYwfwInfo", { ywfw: mstform.getItem("user_regional_center").getRawValue() || '0' }, function (res) {
                console.log('业务范围', res)
                if (res.count == 0) return;

                else {
                    var obj = JSON.parse(res.data);
                    mstform.getItem("user_ywfw").setValue(obj[0].extendObjects.phid);
                    mstform.getItem("user_ywfw").setRawValue(obj[0].extendObjects.u_ywcj_name);
                    mstform.getItem("user_bus_range_no").setValue(obj[0].extendObjects.u_ywcj_no);

                }

            });
        });

    }
    else if (schemeid == '8570000000000093' || schemeid == '8570000000000347') {

        toolbar.get("imp").setText("引用中标商机");
        mstform.getItem('ApproxContractFc').userSetMustInput(true);
        mstform.getItem('user_sjbm').userSetMustInput(true);
        mstform.getItem('user_sjmc').userSetMustInput(true);
        mstform.getItem('user_ser_mana').userSetMustInput(true)
        mstform.getItem('user_xrxs').userSetMustInput(true)

    }


    if (otype == "add" || otype == "copy") {
        // user_country.setValue("1");
        // BatchBindCombox([mstform.getItem("user_country")]);
        mstform.getItem("user_stage").setValue('8570000000000782');
        mstform.getItem("user_stage").setRawValue('待启动');

        var Cat = mstform.getItem("CatPhId").getValue();
        mstform.getItem("PhidOrg").setValue(Cat);


        execServer("getOrgInfo", { zz: Cat }, function (res) {
            if (res.count > 0) {
                var obj = JSON.parse(res.data);
                user_division.setValue(obj[0].extendObjects.user_devision);
                user_division.setRawValue(obj[0].extendObjects.oname);
                PhIdType.setValue(obj[0].extendObjects.user_pc_type);
                PhIdType.setRawValue(obj[0].extendObjects.type_name);
                BatchBindCombox([mstform.getItem("user_devision")]);
                BatchBindCombox([mstform.getItem("PhIdType")]);
                console.log(PhIdType);
            } else {
                user_division.setValue(Cat);
                user_division.setRawValue(mstform.getItem("CatPhId").getRawValue());
            }
            BatchBindCombox([mstform.getItem("user_devision")]);
            BatchBindCombox([mstform.getItem("PhIdType")]);
        });
        execServer("GetLRCenter", { zz: Cat }, function (res) {
            if (res.count > 0) {
                var obj = JSON.parse(res.data);
                user_profit_center_no.setValue(obj[0].extendObjects.u_lrzx_no);
                user_lrzx.setValue(obj[0].extendObjects.u_lrzx_name);
            }
        });
        if (PhIdFiOcode.getValue() > "1") {
            execServer(
                "GetCostCenter",
                { zz: Cat, org: PhIdFiOcode.getValue() },
                function (res) {
                    if (res.count > 0) {
                        var obj = JSON.parse(res.data);
                        user_cost_center_no.setValue(obj[0].extendObjects.u_cbzx_no);
                        user_cbzx.setValue(obj[0].extendObjects.u_cbzx_name);
                    }
                }
            );
        }
    }

    if (otype == "add") {
        Stat.setValue("sts");
        BatchBindCombox([Stat]);
        //   CatPhId.setValue($appinfo.orgID);
        mstform.getItem("user_fygk").setValue(0.2);
        mstform.getItem("user_liquidation").setValue('0');
        mstform.getItem("user_srbl").setValue(0);
        mstform.getItem('user_srbl').setVisible(false)
        mstform.getItem('user_fygk').setVisible(false);
        mstform.getItem('user_liquidation').setVisible(false);
        mstform.getItem('user_xlxm').setValue('1');
    }
    else if (otype == 'edit') {
        mstform.on("dataready", function () {
            if (mstform.getItem("user_ywlx").getValue() == 8570000000000357) {
                mstform.getItem('ApproxContractFc').setVisible(false);
                mstform.getItem('ApproxContractFc').userSetMustInput(false);
                mstform.getItem('PhIdCompany').userSetReadOnly(false)
                mstform.getItem('user_dslb').userSetReadOnly(false)
                mstform.getItem('user_sjbm').userSetMustInput(false);
                mstform.getItem('user_sjmc').userSetMustInput(false);
                //  mstform.getItem ('PhIdCompany').userSetMustInput(false);   
                mstform.getItem('PcNo').userSetReadOnly(false)
                mstform.getItem('user_country').userSetReadOnly(false)
                mstform.getItem('user_province').userSetReadOnly(false)
                mstform.getItem('user_city').userSetReadOnly(false)
                mstform.getItem('user_region').userSetReadOnly(false)
                mstform.getItem('user_product_line').userSetReadOnly(false)
                mstform.getItem('user_industry_line').userSetReadOnly(false)
                mstform.getItem('user_regional_center').userSetReadOnly(false)
                mstform.getItem('VirtualFlg').setVisible(false);
                mstform.getItem('user_pc_js_mode').setVisible(false);
                mstform.getItem('user_sg_type').setVisible(false);
                mstform.getItem('user_yffzr').setVisible(false);
                mstform.getItem('user_xrsq').setVisible(false);
                mstform.getItem('user_xrxs').setVisible(false);
                mstform.getItem('user_xrxs').userSetMustInput(false);

            }

        });
    }


    mstform.getItem('user_implementpro').setVisible(false);
    if (mstform.getItem("user_ywlx").getValue() == '8570000000000354' ||
        mstform.getItem("user_ywlx").getValue() == '8570000000000351' ||
        mstform.getItem("user_ywlx").getValue() == '8570000000000353') {
        mstform.getItem("user_implementpro").setValue('1');
    } else {
        mstform.getItem("user_implementpro").setValue('0');
    }
    Stat.addListener("change", function (args) {
        console.log(args, "???argss");
    });


    //获取人员信息
    async function getPerponInfo(phid) {
        let map = {}
        await execServer("getPerponInfo_1", { phid }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            console.log(`查询成功`, {
                CNo: _data.bill_no,
                CName: _data.bill_name,
                EmpId: _data.phid,
                PhIdOcode: _data.CBoo,
                PhIdEmp: _data.phid,
                user_is_system: "1",
                PhIdOcode: _data.cboo,
                SexNo: _data.sexno,
                PhidDept: _data.dept,
                PhidDept_EXName: _data.dept_exname,
                MobileNumber: _data.mobile1,
                CardNo: _data.cardno,
                CardType: _data.cardtype,
                // ProjStation:_data.user_position,
                // ProjStation_EXName:_data.user_position_exname
            });
            map = {
                CNo: _data.bill_no,
                CName: _data.bill_name,
                EmpId: _data.phid,
                PhIdOcode: _data.CBoo,
                PhIdEmp: _data.phid,
                user_is_system: "1",
                SexNo: _data.sexno,
                PhidDept: _data.dept,
                PhidDept_EXName: _data.dept_exname,
                MobileNumber: _data.mobile1,
                CardNo: _data.cardno,
                CardType: _data.cardtype,
                // ProjStation:_data.user_position,
                // ProjStation_EXName:_data.user_position_exname
            }
        })
        return map
    }
    const key_ = ["ProjectManager", "user_yffzr", "user_xrxs", "user_xrsq", "user_ser_mana"];
    function autoPerInfo() {
        key_.forEach(async (item) => {
            if (mstform.getItem(item).getValue()) {
                switch (item) {
                    case "ProjectManager":
                        ProjectManager = await getPerponInfo(mstform.getItem(item).getValue())
                        break;
                    case "user_yffzr":
                        user_yffzr = await getPerponInfo(mstform.getItem(item).getValue())
                        break;
                    case "user_xrxs":
                        console.log('为何报错', await getPerponInfo(mstform.getItem(item).getValue()));
                        user_xrxs = await getPerponInfo(mstform.getItem(item).getValue())
                        break;
                    case "user_xrsq":
                        user_xrsq = await getPerponInfo(mstform.getItem(item).getValue())
                        break;
                    case "user_ser_mana":
                        user_ser_mana = await getPerponInfo(mstform.getItem(item).getValue())
                        break;
                }
                await isAddOrDelete()
            } else {
                console.log(`为空的呢`);
            }
        });
    }


    mstform.on("impdataready", async function () {
        console.log(`发生引用`);
        BatchBindCombox([mstform.getItem("user_division")]);
        BatchBindCombox([mstform.getItem("user_sqgw")]);
        BatchBindCombox([mstform.getItem("user_xsjl")]);
        BatchBindCombox([mstform.getItem("user_industry_line")]);
        BatchBindCombox([mstform.getItem("user_hydl")]);
        BatchBindCombox([mstform.getItem("user_product_line")]);
        BatchBindCombox([mstform.getItem("user_regional_center")]);
        BatchBindCombox([mstform.getItem("user_dslb")]);
        BatchBindCombox([mstform.getItem("user_xrxs")]);
        BatchBindCombox([mstform.getItem("user_xrsq")]);
        BatchBindCombox([mstform.getItem("user_ywfw")]);

        BatchBindCombox([user_country]);
        BatchBindCombox([user_province]);
        BatchBindCombox([user_city]);
        BatchBindCombox([user_region]);

        execServer("getYzMc", { cust: mstform.getItem("user_custom_name").getValue() || 0 }, function (res) {
            // 首先检查请求是否成功以及是否有数据返回
            if (res.count == 0) return;
            else {
                var obj = JSON.parse(res.data);
                mstform.getItem("PhIdCompany").setValue(obj[0].extendObjects.phid_ent);
                mstform.getItem("PhIdCompany").setRawValue(obj[0].extendObjects.compname);
            }

        });
        setTimeout(async () => {
            const ywfwValue = mstform.getItem("user_regional_center").getRawValue() || '';
            console.log('传递的参数 ywfw:', ywfwValue); // 确认参数是否正确
            execServer("GetYwfwInfo", { ywfw: mstform.getItem("user_regional_center").getRawValue() || '0' }, function (res) {
                console.log('业务范围', res)
                if (res.count == 0) return;

                else {
                    var obj = JSON.parse(res.data);
                    mstform.getItem("user_ywfw").setValue(obj[0].extendObjects.phid);
                    mstform.getItem("user_ywfw").setRawValue(obj[0].extendObjects.u_ywcj_name);
                    mstform.getItem("user_bus_range_no").setValue(obj[0].extendObjects.u_ywcj_no);

                }

            });

        }, 1000);


        setTimeout(async () => {
            console.log('bbbbbbbbbbbbbbbbb', mstform.getItem("user_sjbm").getValue())
            if (mstform.getItem("user_sjbm").getValue()) {
                console.log('aaa', mstform.getItem("user_sjbm").getValue())

                SjGetGxr(mstform.getItem("user_sjbm").getValue())

            }

        }, 2000);
        //自动生成团队人员 ， 如果每点击帮助之前就自动获取相关信息
        autoPerInfo()

        // execServer(
        //     "GetStakeholdersInfo",
        //     { sj: mstform.getItem("user_sjbm").getValue() },
        //     function (res) {
        //         if (res.count == 0) return

        //         var obj = JSON.parse(res.data);
        //         mstform.getItem("user_gxrid").setValue(obj[0].extendObjects.phid);

        //     }
        // );



    });


    mstform.getItem("user_ywlx").addListener("helpselected", function () {
        if (mstform.getItem("user_ywlx").getValue() == 8570000000000357) {
            mstform.getItem('VirtualFlg').setVisible(false);
            mstform.getItem('user_pc_js_mode').setVisible(false);
            mstform.getItem('user_sg_type').setVisible(false);
            mstform.getItem('user_yffzr').setVisible(false);
            mstform.getItem('user_xrsq').setVisible(false);
            mstform.getItem('user_xrxs').setVisible(false);
            mstform.getItem('user_xrxs').userSetMustInput(false);
            Ext.getCmp("toolbar").get("imp").hide();
        }
        else {

            mstform.getItem('VirtualFlg').setVisible(true);
            mstform.getItem('user_pc_js_mode').setVisible(true);
            mstform.getItem('user_sg_type').setVisible(true);
            mstform.getItem('user_yffzr').setVisible(true);
            mstform.getItem('user_xrsq').setVisible(true);

            mstform.getItem('user_xrxs').setVisible(true);
            mstform.getItem('user_xrxs').userSetMustInput(true);
        }
    });



    user_product_line.addListener("change", function () {
        BatchBindCombox([mstform.getItem("user_product_line")]);
    });

    mstform.getItem("user_sjbm").addListener("change", function () {
        mstform.getItem("PcNo").setValue(mstform.getItem("user_sjbm").getValue());
    });

    mstform.getItem("user_ywfw").addListener("helpselected", function (obj) {
        mstform.getItem("user_bus_range_no").setValue(obj.data.u_ywcj_no);
    });

    mstform.getItem("CatPhId").addListener("helpselected", function () {
        execServer("GetLRCenter", { zz: mstform.getItem("CatPhId").getValue() }, function (res) {
            if (res.count > 0) {
                var obj = JSON.parse(res.data);
                user_profit_center_no.setValue(obj[0].extendObjects.u_lrzx_no);
                user_lrzx.setValue(obj[0].extendObjects.u_lrzx_name);
            }

            mstform.getItem("PhidOrg").setValue(mstform.getItem("CatPhId").getValue());

        });

        execServer("getOrgInfo", { zz: mstform.getItem("CatPhId").getValue() }, function (res) {
            if (res.count > 0) {
                var obj = JSON.parse(res.data);
                user_division.setValue(obj[0].extendObjects.user_devision);
                user_division.setRawValue(obj[0].extendObjects.oname);
                PhIdType.setValue(obj[0].extendObjects.user_pc_type);
                PhIdType.setRawValue(obj[0].extendObjects.type_name);
                BatchBindCombox([mstform.getItem("user_devision")]);
                BatchBindCombox([mstform.getItem("PhIdType")]);
                console.log(PhIdType);
            } else {
                user_division.setValue(Cat);
                user_division.setRawValue(mstform.getItem("CatPhId").getRawValue());
            }
            BatchBindCombox([mstform.getItem("user_devision")]);
            BatchBindCombox([mstform.getItem("PhIdType")]);
        });
    });

    mstform.getItem("PhIdFiOcode").on('beforetriggerclick', function (eOp, ignoreBeforeEvent) {
        if (Ext.isEmpty(mstform.getItem("user_ywlx").getValue())) {
            Ext.Msg.alert('提示', '请先选择项目业务类型！');
            return false;
        }
    });

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // mstform.getItem("user_ywlx").addListener("helpselected", function () {
    //     const currentDate = new Date();
    //     const currentYear = currentDate.getFullYear();

    //     if (mstform.getItem("user_ywlx").getValue() == 8570000000000357) {
    //         execServer("GetWXPC_count", { dt: currentYear}, function (res) {
    //             if (res.count > 0) {
    //                 mstform.getItem("PcNo").setValue('WX' + currentYear+(res.data[0].xmsl||0+1))
    //             }

    //         });
    //     }
    //     if( mstform.getItem("PhIdFiOcode").getValue()>0){
    //         costcenter()
    //     }
    //     if(mstform.getItem("user_ywlx").getValue()==8570000000000357){
    //         mstform.getItem ('user_ser_mana').userSetMustInput(false); 
    //     }
    //     else{
    //         mstform.getItem ('user_ser_mana').userSetMustInput(true); 

    //     }

    // });

    mstform.getItem("user_ywlx").addListener("helpselected", function () {
        const currentDate = new Date();
        const currentYear = currentDate.getFullYear();
        const userYwlxValue = mstform.getItem("user_ywlx").getValue();

        // 判断业务类型是否为特定值
        if (userYwlxValue == 8570000000000357) {
            execServer("GetWXPC_count", { dt: currentYear }, function (res) {
                var data = JSON.parse(res.data)
                if (res.count > 0) {
                    // 格式化 xmsl 为 4 位数字字符串，并加 1
                    const newXmsl = String((data[0].extendObjects.xmsl || 0) + 1).padStart(4, '0');
                    mstform.getItem("PcNo").setValue('WX' + currentYear + newXmsl);
                }
            });
            mstform.getItem('user_ser_mana').userSetMustInput(false);
        } else {
            mstform.getItem('user_ser_mana').userSetMustInput(true);
        }
        if (mstform.getItem("PhIdFiOcode").getValue() > 0) {
            costcenter();
        }
    });

    mstform.getItem("PhIdFiOcode").addListener("helpselected", function () {
        costcenter()
        mstform.getItem("user_jzgs").setValue(mstform.getItem("PhIdFiOcode").getValue())
        mstform.getItem("user_jzgs").setRawValue(mstform.getItem("PhIdFiOcode").getRawValue())
        mstform.getItem("user_bzgs").setValue(mstform.getItem("PhIdFiOcode").getValue())
        mstform.getItem("user_bzgs").setRawValue(mstform.getItem("PhIdFiOcode").getRawValue())
    });

    formProjectTableSummary.getItem("CountryId").setValue(1);
    formProjectTableSummary.getItem("CountryId").setRawValue("中国");

    if (otype == 'edit' || otype == 'view') {
        var mstform = Ext.getCmp("formProjectTableMst");
        mstform.on("dataready", function () {

            BatchBindCombox([mstform.getItem("CatPhId")]);
            BatchBindCombox([mstform.getItem("VirtualFlg")]);
            BatchBindCombox([mstform.getItem("ProjectManager")]);
            BatchBindCombox([mstform.getItem("PhIdCompany")]);
            BatchBindCombox([mstform.getItem("Stat")]);

            if (mstform.getItem("user_sjbm").getValue() > 0) {
                SjGetGxr(mstform.getItem("user_sjbm").getValue())

            }
            PcGetInfo(busid)
            tabPanel.setActiveTab(1);
        });
    }
    // user_industry_line.addListener("helpselected", function () {
    //     execServer(
    //         "GetHyxinfo",
    //         { hyx: user_industry_line.getValue() },
    //         function (res) {
    //             if (res.count > 0) {
    //                 var obj = JSON.parse(res.data);
    //                 user_profit_center_no.setValue(obj[0].extendObjects.u_lrzx_no);
    //                 user_profit_center_name.setValue(obj[0].extendObjects.u_cpx_name);
    //             }
    //         }
    //     );
    // });
    ///利润中心

    user_province.on("beforetriggerclick", function (eOp, ignoreBeforeEvent) {
        //选择合同前提示先选择项目
        user_province.setOutFilter({
            nationid: mstform.getItem("user_country").getValue(),
        });
        if (Ext.isEmpty(mstform.getItem("user_country").getValue())) {
            Ext.Msg.alert("提示", "请先选择国家！");
            return false;
        }
    });
    user_city.on("beforetriggerclick", function (eOp, ignoreBeforeEvent) {
        //选择合同前提示先选择项目
        user_city.setOutFilter({
            provinceno: mstform.getItem("user_province").getValue(),
        });
        if (Ext.isEmpty(mstform.getItem("user_province").getValue())) {
            Ext.Msg.alert("提示", "请先选择省份！");
            return false;
        }
    });
    user_region.on("beforetriggerclick", function (eOp, ignoreBeforeEvent) {
        //选择合同前提示先选择项目

        user_region.setOutFilter({
            cityno: mstform.getItem("user_city").getValue(),
        });

        if (Ext.isEmpty(mstform.getItem("user_city").getValue())) {
            Ext.Msg.alert("提示", "请先选择城市！");
            return false;
        }
    });

    user_province.addListener("helpselected", function () {
        formProjectTableSummary
            .getItem("ProvinceId")
            .setValue(user_province.getValue());
        BatchBindCombox([formProjectTableSummary.getItem("ProvinceId")]);
    });
    user_city.addListener("helpselected", function () {
        formProjectTableSummary.getItem("CityId").setValue(user_city.getValue());
        BatchBindCombox([formProjectTableSummary.getItem("CityId")]);
    });
    user_region.addListener("helpselected", function () {
        formProjectTableSummary
            .getItem("RegionId")
            .setValue(user_region.getValue());
        BatchBindCombox([formProjectTableSummary.getItem("RegionId")]);
    });


    ////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////
    if (otype == 'edit' || otype == 'view' || otype == 'add') {
        mstform.on("dataready", function () {
            tabPanel.setActiveTab(1);
            XMTD();

        });
    }
    if (otype == 'add') {
        mstform.getItem("ProjectManager").addListener("helpselected", function () {
            tabPanel.setActiveTab(1);
            XMTD();
        });
    }


    function XMTD() {
        var dgrid = Ext.getCmp("gridEmpChgOther");
        dgrid.getColumn("ProjStation_EXName").getEditor().addListener('helpselected', function () {
            var data = dgrid.getSelectionModel().getSelection();
            var gw = data[0].get('ProjStation');
            if (gw == 1257) {
                data[0].set('PhIdRole', "8570000000000328");
                data[0].set('PhIdRoles', "8570000000000328");
                data[0].set('PhIdRole_EXName', '项目经理');

            }
            else if (gw == 1267) {
                data[0].set('PhIdRole', "8570000000000326");
                data[0].set('PhIdRoles', "8570000000000326");
                data[0].set('PhIdRole_EXName', '销售经理');

            }
            else if (gw == 1263) {
                data[0].set('PhIdRole', "8570000000000335");
                data[0].set('PhIdRoles', "8570000000000335");
                data[0].set('PhIdRole_EXName', '安全员');

            }
            else if (gw == 1265) {
                data[0].set('PhIdRole', "8570000000000336");
                data[0].set('PhIdRoles', "8570000000000336");
                data[0].set('PhIdRole_EXName', '仓库管理员');

            }
            else if (gw == 8570000000001309) {
                data[0].set('PhIdRole', "8570000000000331");
                data[0].set('PhIdRoles', "8570000000000331");
                data[0].set('PhIdRole_EXName', '服务经理');

            }
            else if (gw == 1266) {
                data[0].set('PhIdRole', "8570000000000337");
                data[0].set('PhIdRoles', "8570000000000337");
                data[0].set('PhIdRole_EXName', '资料员');

            }
            else if (gw == 1262) {
                data[0].set('PhIdRole', "8570000000000333");
                data[0].set('PhIdRoles', "8570000000000333");
                data[0].set('PhIdRole_EXName', '项目总工');

            }
            else if (gw == 1260) {
                data[0].set('PhIdRole', "8570000000000314");
                data[0].set('PhIdRoles', "8570000000000314");
                data[0].set('PhIdRole_EXName', '服务工程师');

            }
            else if (gw == 1264) {
                data[0].set('PhIdRole', "8570000000000334");
                data[0].set('PhIdRoles', "8570000000000334");
                data[0].set('PhIdRole_EXName', '质量员');

            }
            else if (gw == 1259) {
                data[0].set('PhIdRole', "8570000000000330");
                data[0].set('PhIdRoles', "8570000000000330");
                data[0].set('PhIdRole_EXName', '软件实施工程师');

            }
            else if (gw == 1268) {
                data[0].set('PhIdRole', "8570000000000327");
                data[0].set('PhIdRoles', "8570000000000327");
                data[0].set('PhIdRole_EXName', '售前工程师');

            }
            else if (gw == 1261) {
                data[0].set('PhIdRole', "8570000000000341");
                data[0].set('PhIdRoles', "8570000000000341");
                data[0].set('PhIdRole_EXName', '信号调优工程师');

            }
            else if (gw == 8570000000001305) {
                data[0].set('PhIdRole', "8570000000000345");
                data[0].set('PhIdRoles', "8570000000000345");
                data[0].set('PhIdRole_EXName', '国际业务项目经理');

            }
            else if (gw == 8570000000001308) {
                data[0].set('PhIdRole', "8570000000000354");
                data[0].set('PhIdRoles', "8570000000000354");
                data[0].set('PhIdRole_EXName', '服务工程师');

            }
            else if (gw == 8570000000001307) {
                data[0].set('PhIdRole', "8570000000000346");
                data[0].set('PhIdRoles', "8570000000000346");
                data[0].set('PhIdRole_EXName', '软件实施工程师');

            }
            else if (gw == 8570000000000781) {
                data[0].set('PhIdRole', "8570000000000338");
                data[0].set('PhIdRoles', "8570000000000338");
                data[0].set('PhIdRole_EXName', '项目研发负责人');

            }
        });
    }

    // dgrid.addListener('edit', function (editor, e) {     
    // if (e.originalValue == e.value) {return;}                                   
    // if (e.field == 'ProjStation_EXName' ||e.field == 'ProjStation') {            
    // var record = e.record;                                                   
    // record.set('PhIdRole', 8570000000000328);         
    // record.set('PhIdRole_EXName','项目经理');
    // };                                                                            
    // });   


    //====================================================初始化数据
    function costcenter() {
        if (mstform.getItem("user_ywlx").getValue() == "8570000000000355") {
            execServer(
                "GetCostCenter",
                { zz: mstform.getItem("CatPhId").getValue(), org: PhIdFiOcode.getValue() },
                function (res) {
                    if (res.count == 0) return;
                    else if (res.count > 0) {
                        var obj = JSON.parse(res.data);
                        user_cost_center_no.setValue(obj[0].extendObjects.u_cbzx_no);
                        user_cbzx.setValue(obj[0].extendObjects.u_cbzx_name);
                        user_budget_org_no.setValue(obj[0].extendObjects.u_yszz_no);
                        user_yszz.setValue(obj[0].extendObjects.u_yszz_name);
                    }
                }
            );
        }
        else {
            execServer(
                "GetCostCenter",
                { zz: mstform.getItem("CatPhId").getValue(), org: PhIdFiOcode.getValue() },
                function (res) {
                    if (res.count == 0) return;
                    else if (res.count > 0) {
                        var obj = JSON.parse(res.data);
                        user_cost_center_no.setValue(obj[0].extendObjects.u_cbzx_no);
                        user_cbzx.setValue(obj[0].extendObjects.u_cbzx_name);
                        user_budget_org_no.setValue(obj[0].extendObjects.u_yszz_no);
                        user_yszz.setValue(obj[0].extendObjects.u_yszz_name);
                    }
                }
            );
        }
        mstform.getItem("user_jzgs").setValue(mstform.getItem("PhIdFiOcode").getValue())
        mstform.getItem("user_jzgs").setRawValue(mstform.getItem("PhIdFiOcode").getRawValue())
        mstform.getItem("user_bzgs").setValue(mstform.getItem("PhIdFiOcode").getValue())
        mstform.getItem("user_bzgs").setRawValue(mstform.getItem("PhIdFiOcode").getRawValue())
    }

    // mstform.getItem("ProjectManager").addListener("helpselected", function (args) {
    //     console.log(args);
    //     const _map = args.data
    //     ProjectManager = _map
    //     isAddOrDelete()
    // })
    // mstform.getItem("user_yffzr").addListener("change", function (args) {
    //     console.log(`项目人员信息change检查`,args.getValue());
    //     const _map = args.data
    //     console.log(`人员信息测试`,args.data);
    //     user_yffzr = _map
    //     isAddOrDelete()
    // })
    // mstform.getItem("user_xrxs").addListener("helpselected", function (args) {
    //     const _map = args.data
    //     user_xrxs = _map
    //     isAddOrDelete()
    // })
    // mstform.getItem("user_xrsq").addListener("helpselected", function (args) {
    //     const _map = args.data
    //     user_xrsq = _map
    //     isAddOrDelete()
    // })
    // mstform.getItem("user_ser_mana").addListener("helpselected", function (args) {
    //     const _map = args.data
    //     user_ser_mana = _map
    //     isAddOrDelete()
    // })


    mstform.getItem("ProjectManager").addListener("change", function (args) {
        autoPerInfo()
    })
    mstform.getItem("user_yffzr").addListener("change", function (args) {
        autoPerInfo()
    })
    mstform.getItem("user_xrxs").addListener("change", function (args) {
        autoPerInfo()
    })
    mstform.getItem("user_xrsq").addListener("change", function (args) {
        autoPerInfo()
    })
    mstform.getItem("user_ser_mana").addListener("change", function (args) {
        autoPerInfo()
    })


    //主逻辑
    async function isAddOrDelete() {
        console.log(ProjectManager, user_yffzr, user_xrxs, user_xrsq, user_ser_mana);
        let m_arr = [ProjectManager.CNo, user_yffzr.CNo, user_xrxs.CNo, user_xrsq.CNo, user_ser_mana.CNo]
        //去除空字符
        m_arr = m_arr.filter((item) => { return item ? true : false })
        const dgrid = Ext.getCmp("gridEmpChgOther")
        console.log(ProjectManager, user_yffzr, user_xrxs, user_xrsq);//打印测试，类型String
        //获取表体内容
        const d_store = dgrid.getStore()
        const _arr = d_store.getRange().reduce((value, item, index) => {
            value.push(item.get("EmpNo"))
            return value
        }, [])
        //拿到补集
        const temp = symmetricDifference(m_arr, _arr)
        //删除行
        d_store.getRange().forEach(item => {
            let i = 0
            let arrs = []
            //判断是否含有重复人员
            d_store.getRange().forEach(el => {
                if (item.get("EmpNo") == el.get("EmpNo")) {
                    i++
                    arrs.push(el)
                }
            })
            //是否法相相同行，如果有，只保留系统新增行
            if (i == 2) {

                arrs.forEach(er => {
                    if (er.get("user_is_system") == "1") {
                        d_store.remove(er)
                    }
                })
            }
            //删除行
            if (temp[1].indexOf(item.get("EmpNo")) != -1) {
                d_store.remove(item)
            }
        })
        //增加行
        temp[0].forEach(item => {
            const _tt = [ProjectManager, user_yffzr, user_xrxs, user_xrsq, user_ser_mana]
            let _map = {}
            _tt.forEach(elem => {
                if (elem.CNo == item) {
                    _map = elem
                }
            })
            d_store.insert(d_store.getRange().length, {
                EmpNo: item,
                SName: _map.CName,
                user_is_system: "1",
                Sex: _map.SexNo,
                Sex_EXName: _map.SexNo == '1' ? '男' : '女',
                PhIdOcode: _map.PhIdOcode,
                PhIdDept: _map.PhidDept,
                PhIdDept_EXName: _map.PhidDept_EXName,
                Hdt: _map.MobileNumber,
                IDcard: _map.CardNo,
                Xh_EXName: _map.CardType,
                LeaveFlg: "0",
                PhIdEmp: _map.PhIdEmp,
                RelType: "1",
                DelFlg:"0"

            })//加相加的字段args.data数据
        })
    }

    //取两数组补集
    function symmetricDifference(arr1, arr2) {
        // 过滤出 arr1 中不在 arr2 里的元素
        const diff1 = arr1.filter(item => !arr2.includes(item));
        // 过滤出 arr2 中不在 arr1 里的元素
        const diff2 = arr2.filter(item => !arr1.includes(item));
        // 输出二维数组
        return [diff1, diff2];
    }
}

//===========================================================================================================



//------生成主键函数(格式为日期时间毫秒+流水号)------
function generateId(sequence) {
    //获取当前时间
    const date = new Date();
    // 格式化日期为 YYMMDD
    const year = date.getFullYear().toString().slice(-2);
    const month = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date.getDate().toString().padStart(2, "0");
    const dateStr = `${year}${month}${day}`;
    // 格式化时间为 HHMMSS
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    const seconds = date.getSeconds().toString().padStart(2, "0");
    const timeStr = `${hours}${minutes}${seconds}`;
    // 获取毫秒数，并确保是2位数
    const milliseconds = date
        .getMilliseconds()
        .toString()
        .padStart(3, "0")
        .slice(0, 2);
    // 格式化流水号为3位
    const sequenceStr = sequence.toString().padStart(3, "0");
    // 拼接日期、时间、毫秒和流水号
    const phid = `${dateStr}${timeStr}${milliseconds}${sequenceStr}`;
    return phid;
}

//增加表头tab页
function addTabs(mstform, tabPanel, toolbar) {
    //定义model
    var pc_stakeholders_model = Ext.define("JdNextPlanmodel", {
        extend: "Ext.data.Model",
        fields: [
            {
                name: "phid",
                type: "bigInt",
                mapping: "phid",
            },
            {
                name: "mstphid",
                type: "bigInt",
                mapping: "mstphid",
            },
            {
                name: "identity",
                type: "string",
                mapping: "identity",
            },
            {
                name: "u_sjbh",
                type: "string",
                mapping: "u_sjbh",
            },
            {
                name: "u_opp_name",
                type: "string",
                mapping: "u_opp_name",
            },
            {
                name: "u_gxr_xm",
                type: "string",
                mapping: "u_gxr_xm",
            },
            {
                name: "u_mobile_phone",
                type: "string",
                mapping: "u_mobile_phone",
            },
            {
                name: "u_customer_name",
                type: "string",
                mapping: "u_customer_name",
            },
            {
                name: "u_dept",
                type: "string",
                mapping: "u_dept",
            },
            {
                name: "u_position",
                type: "string",
                mapping: "u_position",
            },
            {
                name: "gender",
                type: "string",
                mapping: "gender",
            },
            {
                name: "gxr_level",
                type: "string",
                mapping: "gxr_level",
            },
            {
                name: "gxcsq",
                type: "string",
                mapping: "gxcsq",
            },
            {
                name: "is_stakeholder",
                type: "string",
                mapping: "is_stakeholder",
            },
            {
                name: "u_response_person",
                type: "string",
                mapping: "u_response_person",
            },
            {
                name: "zt",
                type: "string",
                mapping: "zt",
            },
        ],
    });

    //定义store
    var pc_stakeholders_store = Ext.create("Ext.ng.JsonStore", {
        model: pc_stakeholders_model,
    });
    //干系人 grid
    var pc_stakeholders = Ext.create("Ext.ng.GridPanel", {
        title: "干系人",
        id: "pc_stakeholders",
        region: "center",
        stateful: false,
        margin: "0 0 0 0",
        isInit: true,
        width: 1200,
        split: false,
        MaxHeight: 1000,
        stateId: "pc_stakeholders", //所有单据不允许重复
        store: pc_stakeholders_store,
        buskey: "phid", //对应的业务表主键属性
        otype: otype,
        columnLines: true,
        // tbar: [{
        //     xtype: 'button',
        //     itemId: 'addrow',
        //     text: '增行',
        //     iconCls: "icon-AddRow",
        //     handler: function () {
        //         var newRecord = {
        //             'phid': generateId(pc_stakeholders_store.getCount() + 1).toString(),
        //             // 可以在这里添加其他初始字段
        //         };
        //         pc_stakeholders_store.insert(pc_stakeholders_store.getCount(), [newRecord]);
        //     }
        // }, {
        //     xtype: 'button',
        //     itemId: 'delrow',
        //     text: '删行',
        //     iconCls: "icon-DeleteRow",
        //     handler: function () {
        //         var data = pc_stakeholders.getSelectionModel().getSelection();
        //         Ext.Array.each(data, function (record) {
        //             pc_stakeholders_store.remove(record);
        //         });
        //     }
        // }
        // ],

        tbar: [
            {
                xtype: "button",
                itemId: "addgxr",
                text: "修改项目干系人",
                iconCls: "icon-AddRow",
                handler: function () {

                    var pcid = busid;

                    var mstform = Ext.getCmp("formProjectTableMst");
                    var id = mstform.getItem("user_gxrid").getValue();
                    var pc_gxrid = mstform.getItem("user_gxrpcid").getValue();
                    var pcname = mstform.getItem("ProjectName").getValue();

                    // $OpenTab(
                    //     "项目干系人新增",
                    //     C_ROOT +
                    //     "react/index.html#/customform/detail?otype=add&busType=EFORM9000000120&isSso=0&AppTitle=%E9%A1%B9%E7%9B%AE%E5%B9%B2%E7%B3%BB%E4%BA%BA%E7%AE%A1%E7%90%86-%E6%96%B0%E5%A2%9E"
                    // ); // p_form_pc_stakeholders_m.phid_pc.setValue(busid)
                    if (id > 0) {
                        $OpenTab(
                            "项目干系人-修改",
                            C_ROOT +
                            "react/index.html#/customform/detail?id=" +
                            mstform.getItem("user_gxrid").getValue() +
                            "&otype=edit&busType=EFORM9000000120&isSso=0&AppTitle=%E9%A1%B9%E7%9B%AE%E5%B9%B2%E7%B3%BB%E4%BA%BA%E7%AE%A1%E7%90%86-%E4%BF%AE%E6%94%B9&menucode=03b1f31e-3022-4804-8a6f-259450f79308"
                        ); // p_form_pc_stakeholders_m.phid_pc.setValue(busid)
                    }
                    else if (pc_gxrid > 0) {
                        $OpenTab(
                            "项目干系人-修改",
                            C_ROOT +
                            "react/index.html#/customform/detail?id=" +
                            mstform.getItem("user_gxrpcid").getValue() +
                            "&otype=edit&busType=EFORM9000000120&isSso=0&AppTitle=%E9%A1%B9%E7%9B%AE%E5%B9%B2%E7%B3%BB%E4%BA%BA%E7%AE%A1%E7%90%86-%E4%BF%AE%E6%94%B9&menucode=03b1f31e-3022-4804-8a6f-259450f79308"
                        ); // p_form_pc_stakeholders_m.phid_pc.setValue(busid)
                    }
                    else {
                        if (pcid != '0') {

                           
                            $OpenTab(
                                "项目干系人-新增",
                                C_ROOT +
                                "react/index.html#/customform/detail?otype=add&busType=EFORM9000000120&isSso=0&AppTitle=%E9%A1%B9%E7%9B%AE%E5%B9%B2%E7%B3%BB%E4%BA%BA%E7%AE%A1%E7%90%86-%E6%96%B0%E5%A2%9E&treeOcode=8570000000000037&treeOcodeName=%E6%95%B0%E5%AD%97%E6%94%BF%E5%BA%9C%E4%BA%8B%E4%B8%9A%E6%9C%AC%E9%83%A8" +
                                "&treePc=" + encodeURIComponent(pcid) +
                                "&treePcName=" + encodeURIComponent(pcname) +
                                "&menucode=27ea9644-e608-4363-8158-e9243e69ca5b"
                                // +"&u_pc_name=" + pcname
                            ); // p_form_pc_stakeholders_m.phid_pc.setValue(busid)
                        }
                        else {
                            Ext.MessageBox.alert("提示", "请先保存项目！");
                        }
                    }


                },
            },
        ],
        columns: [
            Ext.create("Ext.grid.RowNumberer", { text: "序号", width: 45 }),
            {
                header: Lang.project_table_phid || "主键",
                dataIndex: "phid",
                itemId: "phid",
                width: 100,
                sortable: true,
                hidden: true,
            },
            {
                header: Lang.project_table_phid || "单据主键",
                dataIndex: "mstphid",
                itemId: "mstphid",
                width: 100,
                sortable: true,
                hidden: true,
                readOnly: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "身份",
                dataIndex: "identity",
                itemId: "identity",
                readOnly: true,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "商机编号",
                dataIndex: "u_sjbh",
                itemId: "u_sjbh",
                readOnly: true,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "商机名称",
                dataIndex: "u_opp_name",
                itemId: "u_opp_name",
                readOnly: true,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "干系人姓名",
                dataIndex: "u_gxr_xm",
                itemId: "u_gxr_xm",
                readOnly: true,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "手机号",
                dataIndex: "u_mobile_phone",
                itemId: "u_mobile_phone",
                readOnly: true,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "客户名称",
                dataIndex: "u_customer_name",
                itemId: "u_customer_name",
                readOnly: true,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "部门",
                dataIndex: "u_dept",
                itemId: "u_dept",
                readOnly: true,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "职位",
                dataIndex: "u_position",
                itemId: "u_position",
                readOnly: true,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "性别",
                dataIndex: "gender",
                itemId: "gender",
                readOnly: true,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "层级",
                dataIndex: "gxr_level",
                itemId: "gxr_level",
                readOnly: true,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "客户关系成熟度",
                dataIndex: "gxcsq",
                itemId: "gxcsq",
                readOnly: true,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "是否干系人",
                dataIndex: "is_stakeholder",
                itemId: "is_stakeholder",
                readOnly: true,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "第一责任人",
                dataIndex: "u_response_person",
                itemId: "u_response_person",
                readOnly: true,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "干系人状态",
                dataIndex: "zt",
                itemId: "zt",
                readOnly: true,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "层级",
                dataIndex: "gxr_level",
                itemId: "gxr_level",
                readOnly: true,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
        ],
        plugins: [
            Ext.create("Ext.grid.plugin.CellEditing", {
                clicksToEdit: 1,
            }),
        ],
    });
    //加到tab
    tabPanel.add(pc_stakeholders);

    var pc_cnt_info_model = Ext.define("JdNextPlanmodel", {
        extend: "Ext.data.Model",
        fields: [
            {
                name: "phid",
                type: "bigInt",
                mapping: "phid",
            },
            {
                name: "mstphid",
                type: "bigInt",
                mapping: "mstphid",
            },
            {
                name: "fgs",
                type: "string",
                mapping: "fgs",
            },
            {
                name: "bsc",
                type: "string",
                mapping: "bsc",
            },
            {
                name: "xsry",
                type: "string",
                mapping: "xsry",
            },
            {
                name: "cnt_no",
                type: "string",
                mapping: "cnt_no",
            },
            {
                name: "cnt_name",
                type: "string",
                mapping: "cnt_name",
            },
            {
                name: "cnt_stat",
                type: "string",
                mapping: "cnt_stat",
            },
            {
                name: "ori_cnt_amt",
                type: "string",
                mapping: "ori_cnt_amt",
            },
            {
                name: "kgrq",
                type: "string",
                mapping: "kgrq",
            },
            {
                name: "wgrq",
                type: "string",
                mapping: "wgrq",
            },
            {
                name: "cnt_zbq",
                type: "string",
                mapping: "cnt_zbq",
            },
            {
                name: "zbrq",
                type: "string",
                mapping: "zbrq",
            },
            {
                name: "signdt",
                type: "string",
                mapping: "signdt",
            },
            {
                name: "cpx",
                type: "string",
                mapping: "cpx",
            },
            {
                name: "qdmlr",
                type: "string",
                mapping: "qdmlr",
            },
            {
                name: "cjzz",
                type: "string",
                mapping: "cjzz",
            },
            {
                name: "custom_name",
                type: "string",
                mapping: "custom_name",
            },
            {
                name: "cnt_now_amt",
                type: "string",
                mapping: "cnt_now_amt",
            },
            {
                name: "divison",
                type: "string",
                mapping: "divison",
            },
            {
                name: "area_center",
                type: "string",
                mapping: "area_center",
            },
        ],
    });

    //定义store
    var pc_cnt_info_store = Ext.create("Ext.ng.JsonStore", {
        model: pc_cnt_info_model,
    });
    //合同信息 grid
    var pc_cnt_info = Ext.create("Ext.ng.GridPanel", {
        title: "合同信息",
        id: "pc_cnt_info",
        region: "south",
        stateful: false,
        isInit: true,
        MaxHeight: 800,
        stateId: "pc_cnt_info", //所有单据不允许重复
        store: pc_cnt_info_store,
        buskey: "phid", //对应的业务表主键属性
        otype: otype,
        columnLines: true,
        // tbar: [{
        //     xtype: 'button',
        //     itemId: 'addrow',
        //     text: '增行',
        //     iconCls: "icon-AddRow",
        //     handler: function () {
        //         var newRecord = {
        //             'phid': generateId(pc_cnt_info_store.getCount() + 1).toString(),
        //             // 可以在这里添加其他初始字段
        //         };
        //         pc_cnt_info_store.insert(pc_cnt_info_store.getCount(), [newRecord]);
        //     }
        // }, {
        //     xtype: 'button',
        //     itemId: 'delrow',
        //     text: '删行',
        //     iconCls: "icon-DeleteRow",
        //     handler: function () {
        //         var data = pc_cnt_info.getSelectionModel().getSelection();
        //         Ext.Array.each(data, function (record) {
        //             pc_cnt_info_store.remove(record);
        //         });
        //     }
        // }
        // ],

        columns: [
            Ext.create("Ext.grid.RowNumberer", { text: "序号", width: 45 }),
            {
                header: Lang.project_table_phid || "主键",
                dataIndex: "phid",
                itemId: "phid",
                width: 100,
                sortable: true,
                hidden: true,
            },
            {
                header: Lang.project_table_phid || "单据主键",
                dataIndex: "mstphid",
                itemId: "mstphid",
                width: 100,
                sortable: true,
                hidden: true,
                readOnly: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            // {
            //     header: '分公司',
            //     dataIndex: 'fgs',
            //     itemId: 'fgs',
            //     readOnly: false,
            //     mustInput: false,
            //     width: 100,
            //     sortable: true,
            //     locked: false,
            //     hidden: false,
            //     editor: {
            //         xtype: 'ngText',
            //         allowBlank: true
            //     }
            // }, {
            //     header: '办事处',
            //     dataIndex: 'bsc',
            //     itemId: 'bsc',
            //     readOnly: false,
            //     mustInput: false,
            //     width: 100,
            //     sortable: true,
            //     locked: false,
            //     hidden: false,
            //     editor: {
            //         xtype: 'ngText',
            //         allowBlank: true
            //     }
            // }, {
            //     header: '销售人员',
            //     dataIndex: 'xsry',
            //     itemId: 'xsry',
            //     readOnly: false,
            //     mustInput: false,
            //     width: 100,
            //     sortable: true,
            //     locked: false,
            //     hidden: false,
            //     editor: {
            //         xtype: 'ngText',
            //         allowBlank: true
            //     }
            // },
            {
                header: "合同编号",
                dataIndex: "cnt_no",
                itemId: "cnt_no",
                readOnly: false,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "合同名称",
                dataIndex: "cnt_name",
                itemId: "cnt_name",
                readOnly: false,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "合同状态",
                dataIndex: "cnt_stat",
                itemId: "cnt_stat",
                readOnly: false,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "初始合同额（元）",
                dataIndex: "ori_cnt_amt",
                itemId: "ori_cnt_amt",
                readOnly: false,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngNumber",
                    allowBlank: true,
                },
                align: "right",
                mustInput: false,
                hidden: false,
                renderer: function (val) {
                    return Ext.util.Format.number(val, "000,000,000,000.00");
                },
            },
            //  {
            //     header: '产品线',
            //     dataIndex: 'cpx',
            //     itemId: 'cpx',
            //     readOnly: false,
            //     mustInput: false,
            //     width: 100,
            //     sortable: true,
            //     locked: false,
            //     hidden: false,
            //     editor: {
            //         xtype: 'ngText',
            //         allowBlank: true
            //     }
            // },
            {
                header: "约定开工日期",
                dataIndex: "kgrq",
                itemId: "kgrq",
                readOnly: false,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "约定完工日期",
                dataIndex: "wgrq",
                itemId: "wgrq",
                readOnly: false,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "合同质保期（年）",
                dataIndex: "cnt_zbq",
                itemId: "cnt_zbq",
                readOnly: false,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            {
                header: "中标日期",
                dataIndex: "zbrq",
                itemId: "zbrq",
                readOnly: false,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            // {
            //     header: "合同签订日期",
            //     dataIndex: "signdt",
            //     itemId: "signdt",
            //     readOnly: false,
            //     mustInput: false,
            //     width: 100,
            //     sortable: true,
            //     locked: false,
            //     hidden: false,
            //     editor: {
            //         xtype: "ngText",
            //         allowBlank: true,
            //     },
            // },
            {
                header: "签单毛利率（不含服务费）%",
                dataIndex: "qdmlr",
                itemId: "qdmlr",
                readOnly: false,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngText",
                    allowBlank: true,
                },
            },
            // {
            //     header: "创建组织",
            //     dataIndex: "cjzz",
            //     itemId: "cjzz",
            //     readOnly: false,
            //     mustInput: false,
            //     width: 100,
            //     sortable: true,
            //     locked: false,
            //     hidden: false,
            //     editor: {
            //         xtype: "ngText",
            //         allowBlank: true,
            //     },
            // },
            //  {
            //     header: '客户名称',
            //     dataIndex: 'custom_name',
            //     itemId: 'custom_name',
            //     readOnly: false,
            //     mustInput: false,
            //     width: 100,
            //     sortable: true,
            //     locked: false,
            //     hidden: false,
            //     editor: {
            //         xtype: 'ngText',
            //         allowBlank: true
            //     }
            // },
            {
                header: "合同现额",
                dataIndex: "cnt_now_amt",
                itemId: "cnt_now_amt",
                readOnly: false,
                mustInput: false,
                width: 100,
                sortable: true,
                locked: false,
                hidden: false,
                editor: {
                    xtype: "ngNumber",
                    allowBlank: true,
                },
                align: "right",
                mustInput: false,
                hidden: false,
                renderer: function (val) {
                    return Ext.util.Format.number(val, "000,000,000,000.00");
                },
            },
            // {
            //     header: '事业部',
            //     dataIndex: 'divison',
            //     itemId: 'divison',
            //     readOnly: false,
            //     mustInput: false,
            //     width: 100,
            //     sortable: true,
            //     locked: false,
            //     hidden: false,
            //     editor: {
            //         xtype: 'ngText',
            //         allowBlank: true
            //     }
            // }, {
            //     header: '区域中心',
            //     dataIndex: 'area_center',
            //     itemId: 'area_center',
            //     readOnly: false,
            //     mustInput: false,
            //     width: 100,
            //     sortable: true,
            //     locked: false,
            //     hidden: false,
            //     editor: {
            //         xtype: 'ngText',
            //         allowBlank: true
            //     }
            // },
        ],
        plugins: [
            Ext.create("Ext.grid.plugin.CellEditing", {
                clicksToEdit: 1,
            }),
        ],
    });
    tabPanel.add(pc_cnt_info);
    // let pc_cnt_infoStore = pc_cnt_info.getStore();
    // if (pc_cnt_infoStore.sorters.length == '0') {
    //     var arr = new Array();
    //     for (var i = 0; i < 1; i++) {
    //         arr.push({
    //             phid: generateId(pc_cnt_infoStore.getCount() + 1).toString(),

    //         })
    //     }
    //     pc_cnt_infoStore.removeAll(); //清除单据体内所有数据
    //     pc_cnt_infoStore.insert(pc_cnt_infoStore.getCount(), arr); //将服务端获取的数组内容插入到单据体
    // }
}

function getExtendData() {
    ////干系人
    var pc_stakeholders = Ext.getCmp("pc_stakeholders");
    var extendObj1 = pc_stakeholders.getChange(false);

    var pc_cnt_info = Ext.getCmp("pc_cnt_info");
    var extendObj2 = pc_cnt_info.getChange(false);

    //手动建立的表名
    return {
        pc_stakeholders: JSON.stringify(extendObj1),
        pc_cnt_info: JSON.stringify(extendObj2),
    };
}

// function AllReadyList() {
//     var Toolbar = Ext.getCmp("ext-comp-1036");
//     Toolbar.items.get("adds").on("click", function () {
//         $OpenTab(
//             "项目信息-新增",
//             C_ROOT +
//             "PMS/PC/ProjectTable/ProjectTableEditByAdd?otype=add&mtype=general&schemeid=8570000000000093&ocode=" +
//             $appinfo.orgID +
//             "&projprop=4"
//         );
//         // "PMS/PC/ProjectTable/ProjectTableEditByAdd?otype=add&mtype=general&schemeid=8570000000000093&ocode=" +
//     });
// }
function ruleArrDel(name) {
    return [
        mstform.getItem("ProjectManager").valueModels[0].data.CName,
        mstform.getItem("user_yffzr").valueModels[0].data.CName,
        mstform.getItem("user_xrxs").valueModels[0].data.CName,
        mstform.getItem("user_xrsq").valueModels[0].data.CName,
    ].includes(name);
}


function PcGetInfo(phid) {
    var pc_stakeholders = Ext.getCmp("pc_stakeholders");
    var pc_stakeholders_store = pc_stakeholders.getStore();
    var pc_cnt_info = Ext.getCmp("pc_cnt_info");
    var pc_cnt_info_store = pc_cnt_info.getStore();

    execServer(
        "AccPcGetStakeholdersInfo",
        { pc: phid },
        function (res) {
            if (res.count == 0) return

            var obj = JSON.parse(res.data);
            mstform.getItem("user_gxrpcid").setValue(obj[0].extendObjects.phid);

        }
    );


    execServer(
        "AccPcGetStakeholdersInfo",
        { pc: phid },
        function (res) {
            if (res.count == 0) return
            console.log(res); // 打印整个响应对象以便调试               
            const parsedData = JSON.parse(res.data);
            // 检查parsedData是否为数组以及是否包含元素
            if (Array.isArray(parsedData) && parsedData.length > 0) {
                var arr = [];
                for (let i = 0; i < parsedData.length; i++) {
                    const record = parsedData[i].extendObjects;
                    arr.push({
                        identity: record.identity,
                        u_sjbh: record.u_sjbh,
                        u_opp_name: record.u_opp_name,
                        u_gxr_xm: record.u_gxr_xm,
                        u_mobile_phone: record.u_mobile_phone,
                        u_customer_name: record.u_customer_name,
                        u_dept: record.u_dept,
                        u_position: record.u_position,
                        gender: record.gender,
                        gxcsq: record.gxcsq,
                        is_stakeholder: record.is_stakeholder,
                        u_response_person: record.u_response_person,
                        zt: record.zt,
                        gxr_level: record.gxr_level,
                    });
                }
                pc_stakeholders_store.insert(pc_stakeholders_store.getCount(), arr);
            }
        }
    );

    execServer("PCgetCntInfo", { pc: phid }, function (res) {
        if (res.count == 0) return
        console.log(res); // 打印整个响应对象以便调试
        // 将data字符串解析为JavaScript对象
        const parsedData = JSON.parse(res.data);
        if (Array.isArray(parsedData)) {
            var arr = [];
            for (let i = 0; i < res.count; i++) {
                const record = parsedData[i].extendObjects; // 从extendObjects中获取数据
                arr.push({
                    fgs: record.fgs,
                    bsc: record.bsc,
                    xsry: record.xsry,
                    cnt_no: record.ht_no,
                    cnt_name: record.htmc,
                    cnt_stat: record.stat,
                    ori_cnt_amt: record.cshte,
                    cpx: record.cpx,
                    kgrq: record.kgrq,
                    wgrq: record.wgrq,
                    cnt_zbq: record.user_htbzq,
                    zbrq: record.zbrq,
                    qdmlr: record.qdmllb,
                    cjzz: record.zz,
                    custom_name: record.khmc,
                    cnt_now_amt: record.htxe,
                    divison: record.zz,
                    area_center: record.qyzx,
                    signdt: record.qdrq,
                });
            }
            // 插入数据到存储
            pc_cnt_info_store.insert(pc_cnt_info_store.getCount(), arr);
        }


    });

}


function SjGetGxr(sjbm) {
    var pc_stakeholders = Ext.getCmp("pc_stakeholders");
    var pc_stakeholders_store = pc_stakeholders.getStore();
    var mstform = Ext.getCmp("formProjectTableMst");
    execServer(
        "GetStakeholdersInfo",
        { sj: sjbm },
        function (res) {
            if (res.count == 0) return

            var obj = JSON.parse(res.data);
            mstform.getItem("user_gxrid").setValue(obj[0].extendObjects.phid);

        }
    );


    execServer(
        "GetStakeholdersInfo",
        { sj: sjbm },
        function (res) {
            if (res.count == 0) return
            console.log(res); // 打印整个响应对象以便调试               
            const parsedData = JSON.parse(res.data);
            // 检查parsedData是否为数组以及是否包含元素
            if (Array.isArray(parsedData) && parsedData.length > 0) {
                var arr = [];
                for (let i = 0; i < parsedData.length; i++) {
                    const record = parsedData[i].extendObjects;
                    arr.push({
                        identity: record.identity,
                        u_sjbh: record.u_sjbh,
                        u_opp_name: record.u_opp_name,
                        u_gxr_xm: record.u_gxr_xm,
                        u_mobile_phone: record.u_mobile_phone,
                        u_customer_name: record.u_customer_name,
                        u_dept: record.u_dept,
                        u_position: record.u_position,
                        gender: record.gender,
                        gxcsq: record.gxcsq,
                        is_stakeholder: record.is_stakeholder,
                        u_response_person: record.u_response_person,
                        zt: record.zt,
                        gxr_level: record.gxr_level,
                    });
                }
                pc_stakeholders_store.insert(pc_stakeholders_store.getCount(), arr);
            }
        }
    );

}